package com.example.springboot.test;

import com.example.springboot.exception.BusinessException;
import org.springframework.validation.BindException;
import com.example.springboot.response.CommonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统一异常处理、数据预处理等
 */
@ControllerAdvice
public class ControllerExceptionHandler {

    private static final Logger LOG = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    /**
     * 校验异常统一处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public CommonResponse validExceptionHandler(BindException e) {
        CommonResponse commonResponse = new CommonResponse();
        LOG.warn("参数校验失败：{}", e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        commonResponse.setSuccess(false);
        commonResponse.setMessage(e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
        return commonResponse;
    }

    /**
     * 校验异常统一处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public CommonResponse validExceptionHandler(BusinessException e) {
        CommonResponse commonResponse = new CommonResponse();
        //e.getCode()是获取你写的个异常的枚举，getDesc（）是获得你枚举内的描述信息
        LOG.warn("业务异常：{}", e.getCode().getDesc());
        commonResponse.setSuccess(false);
        commonResponse.setMessage(e.getCode().getDesc());
        return commonResponse;
    }

    /**
     * 校验异常统一处理
     * @param e
     * @return
     */
    //这里是处理那些既不是业务异常也不是参数校验异常的异常，不能出现Exception，出现了就说明你的程序有bug
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CommonResponse validExceptionHandler(Exception e) {
        CommonResponse commonResponse = new CommonResponse();
        //这里打整个e是因为这里是要处理普遍的异常，所以要把整个异常的堆栈信息都打出来。
        LOG.error("系统异常：", e);
        commonResponse.setSuccess(false);
        commonResponse.setMessage("系统出现异常，请联系管理员");
        return commonResponse;
    }
}
